<template>
	<view class="">
		<view class="chatbottomall">
			<view class="chatbottom">
			<image class="img" src="@/static/tabBar/index/say.png"  @tap="saywhat" ></image>
			<button class="elbut" type="primary" icon="success"  v-if="hideright" @touchstart="startRecord" @touchend="endRecord">按住说话</button>
			<uni-easyinput  ref="easyinput" blur class="elinput" borderColor="#ffffff" v-model="inputmsg" @focus="handleFocus" v-if="!hideright" ></uni-easyinput>
			<image class="img" src="@/static/tabBar/index/show.png"  @tap="sendface" v-if="!hideright"></image>
			<image class="img" src="@/static/tabBar/index/add.png"  @tap="addwhat" v-show="!hideright && inputmsg.length==0"></image>
			<view class="text" v-show="!hideright && inputmsg.length!=0" @tap="senddatemsg">
				发送
			</view>
			<view class="sendfacestep" v-if="isshowface">
				<scroll-view scroll-y="true" >
					<view class="sendfacestep">
						<emoji @getemoji="getemoji"></emoji>
					</view>
				</scroll-view>
			</view>
			<view class="bottomadd" v-show="drawer">
				<chatbox :userid="this.userInfo.id" :friendID="this.getfrienddetailid"></chatbox>
			</view>
			</view>

			
		</view>
		
		
	</view>
</template>

<script>
	import emoji from '@/components/emoji/index.vue'
	import chatbox from '@/components/groupboxbottom/index.vue'
	import {mapState} from 'vuex'
	const recorderManager = uni.getRecorderManager();//录音
	const innerAudioContext = uni.createInnerAudioContext();
	import $http from "@/common/api/request.js"
	import _ from 'lodash';
	export default{
		props:['getfrienddetailid'],
		data(){
			return{
				baseurl:"https://zyc618.mynatapp.cc",
				inputmsg:"",
				isshowface:false,
				getemojistring:"",
				hideright:false,
				drawer:false,
				cursorPosition:0,
				voicePath:"",
				time:0,
				getinputstart:0,
				getinputeend:0,
				fixedString:"GDPW"
			}
		},
		components:{
			emoji,chatbox
		},
		methods:{
			saywhat(){
				this.hideright = !this.hideright;
				this.isshowface = false ;
				this.drawer = false;
			},
			sendface(){
				this.isshowface = !this.isshowface ;
				this.drawer = false;
				this.$nextTick(()=>{
					this.getallheight()
				})
				
			},
			addwhat(){
				this.drawer = !this.drawer;
				this.isshowface = false ;
				this.hideright = false;
				this.$nextTick(()=>{
					this.getallheight()
				})
			},
			//动态获取底部高度
			getallheight(){
				const query = uni.createSelectorQuery().in(this);
				query
				  .select(".chatbottomall")
				  .boundingClientRect((dataa) => {
					this.$emit("getheightbottom",dataa.height)
				  })
				  .exec();
			},
			//获取表情包,事件总线
			getemoji(emojiit){
				this.getemojistring=emojiit;
				this.inputmsg+=emojiit;
				// this.addFixedString(emojiit)
			},
			//发送信息回调:
			senddatemsg: _.debounce(function() {
			      // 在这里处理防抖按钮点击事件逻辑
				  uni.$emit("get_stringmsg",JSON.stringify(this.inputmsg));
				  
				  //填写数据库:
				  this.submitmsgdata(0);
				  this.inputmsg = "";
			    }, 500),
			   
			//按住语音start:
			//开始录音
			startRecord() {
				recorderManager.start();
				let i = 0 ;
				this.time = setInterval(()=>{
					i++;
					this.$emit("gettime",i)
					if(i>100){//总时长不超过100s
						clearInterval(this.time);
					}
				},1000)
				this.$emit("getmasklayer",true)//第二个参数控制遮罩层
			},
			//松开语音end
			endRecord() {
				recorderManager.stop();
				clearInterval(this.time);
				this.$emit("getmasklayer",false)//控制遮罩层
				recorderManager.onStop( (res)=> {
					
					//赋值给voicPath
					this.voicePath = res.tempFilePath;
					//事件总线:
					this.updatasendimg(res.tempFilePath);
					
				});
			},
				
			formatDateTime(date) {
			    const year = date.getFullYear();
			    const month = (date.getMonth() + 1).toString().padStart(2, '0');
			    const day = date.getDate().toString().padStart(2, '0');
			    const hours = date.getHours().toString().padStart(2, '0');
			    const minutes = date.getMinutes().toString().padStart(2, '0');
			
			    return `${year}年${month}月${day}日${hours}:${minutes}`;
			},
			//普通文本发送
			submitmsgdata(typess){
				//填写数据库:
				$http.request({
					url: "/add_contentmessageschema",
					method: "POST",
					data: {
						userID: this.userInfo.id,
						groupid:this.getfrienddetailid,
						message:this.inputmsg,
						types:typess
					}
				}).then((res) => {
					console.log(res);
				}).catch((err) => {
					console.log(err);
				})
			},
			//```````输入框 追加表情包
			handleFocus(event) {
			      // 在输入框聚焦时，保存光标位置
			  uni.getSelectedTextRange({
				success: res => {
				  this.cursorPosition = res.end;console.log(this.cursorPosition);
				}
			  })
			},
			addFixedString() {
			  // 获取当前输入框的值
			  let currentValue = this.inputmsg;
			  // 在光标位置前后插入固定字符串
			  this.inputmsg = currentValue.slice(0, this.cursorPosition) +
								this.fixedString + currentValue.slice(this.cursorPosition);
								
			},
			//``````输入框 追加表情包
			//文件命名方式:
			formattedDate() {
				  const rawDate = new Date();
			      const year = rawDate.getFullYear();
			      const month = (rawDate.getMonth() + 1).toString().padStart(2, '0');
			      const day = rawDate.getDate().toString().padStart(2, '0');
			      return `group${year}${month}${day}`;
			    },
			//语音文件上传到服务器:
			updatasendimg(pathfile){
				const uploadTask=uni.uploadFile({
					url: this.baseurl+'/api/files/upload', //仅为示例，非真实的接口地址
					filePath:pathfile,
					name: 'file',
					formData: {
						url: this.formattedDate(),
						pathname:this.userInfo.id + Date.now()
					},
					success: (uploadFileRes) => {
						
						let imgdatalist =JSON.parse(uploadFileRes.data);
						if(imgdatalist.data.code == 200){
							//数据库保存:
							this.savemsg(imgdatalist.data.url);
							
						}
					},
					fail(err) {
						console.log(err);
					}
				});
				
			},
			//一对一语音:数据库保存消息:
			savemsg(mp3url){
				$http.request({
					url: "/add_contentmessageschema",
					method: "POST",
					header:{
						token:true
					},
					data: {
						message: mp3url,
						userID:this.userInfo.id,
						groupid:this.getfrienddetailid,
						types:2//图片格式
					}
				}).then((res) => {
					if(res.code === 200){
						//数据库信息填写完毕才能继续事件请求:
						uni.$emit("get_MP3msg",JSON.stringify(mp3url));
					}else{
						uni.showToast({
							title:"异常",
							icon:"none"
						})
					}
					
				}).catch((err) => {
					console.log(err);
				})
				
			},
		},
		mounted() {
			this.getallheight();
		},
		computed:{
			...mapState({
				userInfo:state=>state.user.userInfo
			})
		}
	}
</script>

<style lang="scss" >
	.chatbottomall{
		position: fixed;
		bottom:0;
		left: 0;
		width: 100%;
		background-color: #eeeeee;
		
	}
	.chatbottom{
		display: flex;
		flex-wrap: wrap;
		align-items: center;
		width: 100%;
		position: relative;
		z-index: 9999;
		background-color: #fff;
		.elbut{
			width: 65%;
			margin-left: 8%;
			font-size: 28rpx;
			line-height: 68rpx;
		}
		.img{
			width: 60rpx;
			height: 60rpx;
			margin-left:10rpx;
			
		}
		
		.elinput{
			width: 65%;
			margin-left: 8%;
			font-size: 28rpx;
			line-height: 60rpx;
		}
		.sendfacestep{
			height: 400rpx;
			background-color: white;
			width: 100%;
		}
		.bottomadd{
			height: 400rpx;
			background-color: #e7e9eb;
			width: 100%;
			
		}
	}
	.text{
		margin-left:10rpx;
		background-color: #769aff;
		color: #fff;
		width: 10%;
		text-align: center;
		font-size: $uni-font-size-lg;
		line-height: 60rpx;
	}
	
</style>